package com.examplemartin.jpademo.controller.good;

import com.examplemartin.jpademo.bean.AjaxResult;
import com.examplemartin.jpademo.bean.Site;
import com.examplemartin.jpademo.pojo.admin.OperatorLogPO;
import com.examplemartin.jpademo.pojo.po.UserPO;
import com.examplemartin.jpademo.pojo.po.good.GoodPO;
import com.examplemartin.jpademo.pojo.po.good.GoodUnit;
import com.examplemartin.jpademo.pojo.po.stock.SummGoodPO;
import com.examplemartin.jpademo.service.GoodService;
import com.examplemartin.jpademo.service.UserService;
import com.examplemartin.jpademo.service.admin.OperatorLogService;
import com.examplemartin.jpademo.service.stock.SummGoodService;
import com.examplemartin.jpademo.util.EntityCheckUtil;
import com.examplemartin.jpademo.util.SessionUtil;
import com.examplemartin.jpademo.util.ValidateMember;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/good")
@Slf4j
public class GoodController {

    @Resource
    private GoodService goodService;

    @Resource
    private OperatorLogService operatorLogService;

    @Resource
    private UserService userService;
    @Resource
    private Site site;

    /**
     * 商品列表
     *
     * @param model
     *
     * @return
     */
    @GetMapping("/goodlist.do")
    public String SupplierListDo(@RequestParam(value = "page", required = false, defaultValue = "0") Integer page, Model model) {
        model.addAttribute("title", "商品列表");
// 计量单位列表
        model.addAttribute("unitname", GoodUnit.UNIT_NAME);
        model.addAttribute("unitvalue", GoodUnit.UNIT_VALUE);

        if (ValidateMember.isEmpty(page) || page == 0) {
            page = 1;
        }

        int pagesize = Integer.parseInt(site.getPageSize());
        if (ValidateMember.isEmpty(pagesize)) {
            pagesize = Integer.MAX_VALUE;
        }
        // 定义 pageable
        Pageable pageable = PageRequest
                .of(page - 1, pagesize, Sort.by("createTime").descending().and(Sort.by("id").descending()));
//        List<GoodPO> all = goodService.findAll();
//        model.addAttribute("goodlist",all);
        // 获取分页
        List<GoodPO> allPage = goodService.findAllPage(pageable);
        // 计算日志总条数
        Long logSize = goodService.countAll();

        Long totalPage = logSize / pagesize;
        if (totalPage * pagesize < logSize) {
            totalPage++;
        }
        Integer currentPage = page;
        model.addAttribute("goodlist", allPage);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentPage", currentPage);

        // 是否出现 前省略号
        Boolean befor_ellipsis = false;
        if (currentPage >= 4) {
            befor_ellipsis = true;
        }
        model.addAttribute("befor_ellipsis", befor_ellipsis);
        // 是否出现 前省略号
        Boolean after_ellipsis = false;
        if ((totalPage - currentPage) > 3) {
            after_ellipsis = true;
        }
        model.addAttribute("after_ellipsis", after_ellipsis);

        // b1 -- current -- a1
        // 分页b1 是否出现
        Boolean b1 = false;
        if (currentPage <= 2) {
            b1 = true;
        }
        model.addAttribute("b1", b1);
        // 分页a1 是否出现
        Boolean a1 = false;
        if ((totalPage - currentPage) <= 2) {
            a1 = true;
        }
        model.addAttribute("a1", a1);
        // 返回最后3页页码
        model.addAttribute("last00", totalPage - 1);
        model.addAttribute("last01", totalPage - 2);
        model.addAttribute("last02", totalPage - 3);
        // 中间页码
        model.addAttribute("mida", currentPage + 1);
        model.addAttribute("midb", totalPage - 1);

        // 中间分页
        Boolean mid = false;
        if (!b1 && !a1) {
            mid = true;
        }
        model.addAttribute("mid", mid);


        return "good/goodlist";
    }

    /**
     * 跳转到添加商品 get
     *
     * @param model
     *
     * @return
     */
    @GetMapping("/addgood.do")
    public String addSupplierDo(Model model) {
        model.addAttribute("title", "新建商品");
        // 计量单位列表
        model.addAttribute("unitname", GoodUnit.UNIT_NAME);
        model.addAttribute("unitvalue", GoodUnit.UNIT_VALUE);
        return "good/addgood";
    }

    @Resource
    private SummGoodService summGoodService;

    /**
     * 添加商品addSupplierAjax Ajax
     *
     * @param goodPO
     *
     * @return
     */
    @PostMapping("/addgood.ajax")
    @ResponseBody
    public AjaxResult addSupplierAjax(@RequestBody GoodPO goodPO) {

        UserPO loninUser = SessionUtil.getLoninUser();
        loninUser = userService.findUserById(loninUser.getId());

        OperatorLogPO operatorLogPO = new OperatorLogPO();
        operatorLogPO.setUser(loninUser);
        operatorLogPO.setCreateTime(new Date());


        // 01 实体检测
        AjaxResult check = EntityCheckUtil.check(goodPO);
        if (check.getCode() != 200) {
            operatorLogPO.setContent("添加商品操作--" + check.getMsg());
            operatorLogService.saveLog(operatorLogPO);
            return AjaxResult.fail(500, check.getMsg());
        }

        // 02 商品是否重复
        List<GoodPO> allByName = goodService.findByNameAndSpec(goodPO.getName(),goodPO.getSpec());
        if (allByName != null && allByName.size() > 0) {
            operatorLogPO.setContent("添加商品操作失败--" + goodPO.getName()+":"+goodPO.getSpec() + "--重名");
            operatorLogService.saveLog(operatorLogPO);
            return AjaxResult.fail(500, "添加商品操作失败--" +  goodPO.getName()+":"+goodPO.getSpec()+ "--重名");
        }

        goodPO.setCreateTime(new Date());
        GoodPO save = goodService.save(goodPO);

        if (save == null) {
            operatorLogPO.setContent("添加商品操作--" + goodPO.getName()+":"+goodPO.getSpec() + ": 商品添加错误,请联系管理员");
            operatorLogService.saveLog(operatorLogPO);


            return AjaxResult.fail(500, "添加商品操作--" + goodPO.getName()+":"+goodPO.getSpec() + ": 商品添加错误,请联系管理员");
        }
        // 添加总库存条目
        SummGoodPO summGoodPO = new SummGoodPO();
        summGoodPO.setGoodspare(0);
        summGoodPO.setGoodcount(0);
        summGoodPO.setGoodPO(save);
        summGoodService.save(summGoodPO);

        operatorLogPO.setContent("成功添加新商品--" + goodPO.getName()+":"+goodPO.getSpec());
        operatorLogService.saveLog(operatorLogPO);
        return AjaxResult.success(200, "成功添加新商品:"+goodPO.getName()+":"+goodPO.getSpec(), null);
    }


    /**
     * 禁用商品 forbidden.ajax
     *
     * @param goodPO
     *
     * @return
     */
    @PostMapping("/goodforbidden.ajax")
    @ResponseBody
    public AjaxResult forbiddenAjax(@RequestBody GoodPO goodPO) {

        OperatorLogPO operatorLogPO = new OperatorLogPO();
        UserPO loninUser = SessionUtil.getLoninUser();
        loninUser = userService.findUserById(loninUser.getId());
        operatorLogPO.setUser(loninUser);
        operatorLogPO.setCreateTime(new Date());

        GoodPO byId = goodService.findById(goodPO.getId());
        if (byId == null) {
            operatorLogPO.setContent("修改商品状态 " + byId.getName() + " 有误");
            operatorLogService.saveLog(operatorLogPO);
            AjaxResult.fail(500, "不能切换状态,传入数据有误");
        }

        byId.setStatus(GoodPO.GOOD_STATUS_LOCKED);
        byId.setUpdateTime(new Date());
        operatorLogPO.setContent("禁用商品" + byId.getName());
        operatorLogService.saveLog(operatorLogPO);

        goodService.save(byId);


        return AjaxResult.success(200, "已禁用", null);
    }

    /**
     * 跳转到编辑 editgood.do
     *
     * @param id
     *
     * @return
     */
    @GetMapping("/editgood.do")
    public String editSupplierDo(Long id, Model model) {
        model.addAttribute("title", "编辑商品信息");
        // 计量单位列表
        model.addAttribute("unitname", GoodUnit.UNIT_NAME);
        model.addAttribute("unitvalue", GoodUnit.UNIT_VALUE);
        GoodPO byId = goodService.findById(id);
        model.addAttribute("good", byId);
        return "good/editgood";

    }

    /**
     * 编辑修改 editgood.ajax
     */
    @PostMapping("/editgood.ajax")
    @ResponseBody
    public AjaxResult editSupplierAjax(@RequestBody GoodPO goodPO) {

        OperatorLogPO operatorLogPO = new OperatorLogPO();
        UserPO loginUser = SessionUtil.getLoninUser();
        loginUser = userService.findUserById(loginUser.getId());
        operatorLogPO.setUser(loginUser);
        operatorLogPO.setCreateTime(new Date());

        GoodPO byId = goodService.findById(goodPO.getId());

        /**

         private Float price=0f; // 商品价格
         */
        byId.setName(goodPO.getName());
        byId.setStatus(goodPO.getStatus());
        byId.setSpec(goodPO.getSpec());
        byId.setPk(goodPO.getPk());
        byId.setUnit(goodPO.getUnit());
        byId.setComment(goodPO.getComment());
//        byId.setPrice(goodPO.getPrice());
        byId.setUpdateTime(new Date());


        AjaxResult check = EntityCheckUtil.check(byId);
        if (check.getCode() != 200) {
            operatorLogPO.setContent("修改商品: " + goodPO.getName()+":<<"+goodPO.getSpec() +">>"+ "失败:" + check.getMsg());
            operatorLogService.saveLog(operatorLogPO);
            return AjaxResult.fail(500, check.getMsg());
        }

        goodService.save(byId);

        operatorLogPO.setContent("成功修改商品: " + goodPO.getName()+":<<"+goodPO.getSpec() +">>");
        operatorLogService.saveLog(operatorLogPO);

        return AjaxResult.success(200, "成功修改", null);
    }
}
